package com.blank.white.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.blank.black.entity.pojo.*;
import com.blank.black.enums.BooleanEnum;
import com.blank.black.mapper.*;
import com.blank.white.common.enums.CachePreEnum;
import com.blank.white.entity.req.ListReq;
import com.blank.white.entity.req.TableInfoReq;
import com.blank.white.entity.vo.ColInfoVO;
import com.blank.white.entity.vo.TableInfoVO;
import com.blank.white.mapper.ConfigMapper;
import com.blank.white.service.IConfigService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.benmanes.caffeine.cache.LoadingCache;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配置服务实现类
 */
@Service
public class ConfigServiceImpl implements IConfigService {
    @Resource
    ConfigMapper configMapper;
    @Qualifier("CACHE_DEFAULT")
    @Resource
    private LoadingCache<String, Object> loadingCache;
    @Resource
    private BlankConfigMapper blankConfigMapper;

    @Resource
    private ConfigColMapper configColMapper;

    @Resource
    private ConfigCriteriaMapper configCriteriaMapper;

    @Resource
    private ConfigJoinMapper configJoinMapper;

    @Resource
    private ConfigJoinRelationMapper configJoinRelationMapper;


    @Override
    public PageInfo<BlankConfig> listTopBlankConfig(ListReq listReq) {
        // pagehelper 分页
        PageHelper.startPage(listReq.getPageNum(), listReq.getPageSize());
        List<BlankConfig> list = configMapper.listTopBlankConfig(listReq);
        return new PageInfo<>(list);
    }

    @Override
    public Integer deleteExampleConfigById(Long id) {
        // 加锁

        List<Long> deleteIdList = new ArrayList<>();
        deleteIdList.add(id);
        // 查询所有子级配置的ID
        List<BlankConfig> childList = blankConfigMapper.listChiildrenById(id);

        if (childList != null && childList.size() > 0) {
            deleteIdList.addAll(childList.stream().map(BlankConfig::getId).collect(Collectors.toList()));
        }

        // 删除example_config
        configMapper.deleteBlankConfigByIds(deleteIdList);
        // 删除 example_config_col
        configMapper.deleteConfigColByConfigIds(deleteIdList);
        // 删除 example_config_criteria
        configMapper.deleteConfigCriteriaByConfigIds(deleteIdList);
        // 删除 example_config_join
        configMapper.deleteConfigJoinByConfigIds(deleteIdList);
        // 删除 example_config_join_relation
        configMapper.deleteConfigJoinRelationByConfigIds(deleteIdList);
        // 解锁
        loadingCache.invalidate(CachePreEnum.CONFIG_ID_LOCK.getName() + id);
        return BooleanEnum.TRUE.getCode();
    }

    @Override
    public PageInfo<TableInfoVO> listTable(TableInfoReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<TableInfoVO> list = configMapper.listTable(req);
        if (CollectionUtils.isNotEmpty(list)) {
            List<ColInfoVO> colInfoVOList = configMapper.listTableCol(list);
            if (CollectionUtils.isNotEmpty(colInfoVOList)) {
                Map<String, ColInfoVO> colMap = colInfoVOList.stream().collect(Collectors.toMap(X -> X.getTableSchema() + "-" + X.getTableName(), X -> X, (k1, k2) -> k1));
                list.forEach(x -> x.setColInfoVOList(colMap.get(x.getTableSchema() + "-" + x.getTableName()).getColInfoVOList()));
            }
        }
        return new PageInfo<TableInfoVO>(list);
    }

    @Override
    public PageInfo<String> listTableSchema(TableInfoReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<String> list = configMapper.listTableSchema(req);
        return new PageInfo<String>(list);
    }

    @Override
    public Long updateBlankConfig(BlankConfig blankConfig) {

        // 删除旧得配置
        this.deleteExampleConfigById(blankConfig.getId());
        // 保存新得配置
        // 拆解 blank，将其变为一个一个的插入对象
        // 保存顶层配置
        configMapper.updateBlankConfig(blankConfig);
        List<ConfigCol> colList = blankConfig.getColList();
        if (CollectionUtils.isNotEmpty(colList)) {
            for (ConfigCol configCol : colList) {
                configCol.setConfigId(blankConfig.getId());
                configMapper.insertConfigCol(configCol);
            }
        }
        List<ConfigCriteria> criteriaList = blankConfig.getCriteriaList();
        if (CollectionUtils.isNotEmpty(criteriaList)) {
            for (ConfigCriteria criteria : criteriaList) {
                criteria.setConfigId(blankConfig.getId());
                configMapper.insertConfigCriteria(criteria);
            }
        }
        List<ConfigJoin> joinList = blankConfig.getJoinList();
        if (CollectionUtils.isNotEmpty(joinList)) {
            for (ConfigJoin configJoin : joinList) {
                configJoin.setConfigId(blankConfig.getId());
                Long configJoinId = configMapper.insertConfigJoin(configJoin);
                List<ConfigJoinRelation> joinRelationList = configJoin.getRelationList();
                for (ConfigJoinRelation configJoinRelation : joinRelationList) {
                    configJoinRelation.setJoinId(configJoin.getId());
                    configMapper.insertConfigJoinRelation(configJoinRelation);
                }
            }
        }

        // 保存子配置
        List<BlankConfig> childList = blankConfig.getChildList();
        if (CollectionUtils.isNotEmpty(childList)) {
            for (BlankConfig config : childList) {
                this.insertBlankConfig(blankConfig.getId(), config);
            }
        }
        return blankConfig.getId();
    }
    @Override
    public Long insertBlankConfig(Long pid, BlankConfig itemConfig) {
        itemConfig.setPid(pid);
        configMapper.insertConfig(itemConfig);
        List<ConfigCol> colList = itemConfig.getColList();
        if (CollectionUtils.isNotEmpty(colList)) {
            for (ConfigCol configCol : colList) {
                configCol.setConfigId(itemConfig.getId());
                configMapper.insertConfigCol(configCol);
            }
        }
        List<ConfigCriteria> criteriaList = itemConfig.getCriteriaList();
        if (CollectionUtils.isNotEmpty(criteriaList)) {
            for (ConfigCriteria criteria : criteriaList) {
                criteria.setConfigId(itemConfig.getId());
                configMapper.insertConfigCriteria(criteria);
            }
        }
        List<ConfigJoin> joinList = itemConfig.getJoinList();
        if (CollectionUtils.isNotEmpty(joinList)) {
            for (ConfigJoin configJoin : joinList) {
                configJoin.setConfigId(itemConfig.getId());
                Long configJoinId = configMapper.insertConfigJoin(configJoin);
                List<ConfigJoinRelation> joinRelationList = configJoin.getRelationList();
                for (ConfigJoinRelation configJoinRelation : joinRelationList) {
                    configJoinRelation.setJoinId(configJoin.getId());
                    configMapper.insertConfigJoinRelation(configJoinRelation);
                }
            }
        }
        List<BlankConfig> childList = itemConfig.getChildList();
        if (CollectionUtils.isNotEmpty(childList)) {
            for (BlankConfig config : childList) {
                this.insertBlankConfig(itemConfig.getId(), config);
            }
        }
        return itemConfig.getId();
    }

}
